package com.ro.model.index;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.redis.Redis;
import com.ro.common.AbstractController;
import com.ro.common.util.CodeUtil;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

public class IndexController extends AbstractController {

    public void index() {
        redirect("/blog/");
    }

    public void login() {
        render("login.html");
    }

    public void loginCheckValue() {
        String value = getPara("value");
        String pass = PropKit.get("pass");
        if (value != null && !"".equals(value) && CodeUtil.Md5(value).equals(pass)) {
            String uuid = UUID.randomUUID().toString();
            Redis.use("ec").setex("uuid", 10, uuid);
            renderJson("{\"key\":\"" + uuid + "\"}");
            return;
        }
        renderJson("fail");
    }

    public void loginSave() {
        String uuid = getPara("uuid","");
        int authTime = getParaToInt("authTime",0);
        if (uuid != null && !"".equals(uuid)) {
            String uuidKey = Redis.use("ec").get("uuid");
            if (uuid.equals(uuidKey)) {
                //设置默认登录过期时间
                if (authTime == 0){
                    String authInvalidTimeStr = PropKit.get("authInvalidTime");
                    authTime = (authInvalidTimeStr == null ||"".equals(authInvalidTimeStr) ? 0 : Integer.parseInt(authInvalidTimeStr)) * 60;
                }else{
                    authTime = authTime * 60;
                }
                String token = UUID.randomUUID().toString();
                setCookie("ISL", token , authTime);
                Redis.use("ec").setex("authToken", authTime, token);
                Redis.use("ec").setex("auth", authTime, true);
                Redis.use("ec").setex("thisTime", authTime,(System.currentTimeMillis() / 1000));
                Redis.use("ec").setex("authTime", authTime, authTime);
                redirect("/blog/manage");
                return;
            }
        }
        redirect("/login");
    }

    public void out() {
        Redis.use("ec").set("auth", null);
        Redis.use("ec").set("authToken", null);
        Redis.use("ec").set("thisTime", null);
        Redis.use("ec").set("authTime", null);
        redirect("/blog/");
    }

}
